package com.jt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@PropertySource("classpath:/redis.properties")
public class RedisConfig {
    /*@Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;*/

    @Value("${redis.nodes}")
    private String nodes;

   @Value("${redis.sentinel}")
    public String sentinel;
//    单独的一个redis配置，下面将会换成redis集群
   /* @Bean
    public Jedis jedis(){
        return new Jedis(host, port);
    }*/
//    使用redis哨兵
   /* @Bean
    public ShardedJedis shardedJedis(){
        List<JedisShardInfo> shards=new ArrayList<>();
        String[] nodeArray=nodes.split(",");
        for (String node:nodeArray){
            String host=node.split(":")[0];
            int port= Integer.parseInt(node.split(":")[1]);
            JedisShardInfo jedisShardInfo=new JedisShardInfo(host,port);
            shards.add(jedisShardInfo);
        }
        return new  ShardedJedis(shards);
    }*/
   @Bean
    public JedisSentinelPool jedisSentinelPool(){
       JedisPoolConfig poolConfig=new JedisPoolConfig();
       poolConfig.setMinIdle(5);
       poolConfig.setMaxIdle(10);
       poolConfig.setMaxTotal(100);

       Set<String> sentinels=new HashSet<>();

       sentinels.add(sentinel);
       return new JedisSentinelPool("mymaster", sentinels,poolConfig);
   }
   @Bean JedisCluster jedisCluster(){
       Set<HostAndPort> nodeSet=new HashSet<>();
       String[] nodeArray=nodes.split(",");
       for (String node:nodeArray){
           String host=node.split(":")[0];
           int port= Integer.parseInt(node.split(":")[1]);
           HostAndPort hostAndPort=new HostAndPort(host, port);
           nodeSet.add(hostAndPort);
       }
       return new JedisCluster(nodeSet);
   }





}
